package com.training.bowlapp.presentation;

import java.io.Serializable;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.training.bowlapp.service.UserService;
import com.training.persistence.entity.Player;

@Component("userBean")
@Scope("session")
public class UserBean implements Serializable {

	public static final String ERROR = "login";

	private Player player;

	@Autowired
	private UserService userService;

	public UserBean() {
		player = new Player();
	}

	public String loginUser() {
		// server-side validation
		// Check Username and Password
		if (StringUtils.isEmpty(player.getUserName())
				|| StringUtils.isEmpty(player.getPassword())) {
			return ERROR;
		}
		// Check Password
		// e.g. miniumn 8 characters and must contains both numeric and
		// character
		if (!this.isPasswordValid(player.getPassword())) {
			return ERROR;
		}

		// Check Player info in the DB
		if (!userService.isPlayerValid(player)) {
			return ERROR;
		}

		player = userService.loginPlayer(player.getUserName(),
				player.getPassword());

		return "user/index";
	}

	
	public String selectUser(String userName){
		player = userService.findPlayer(userName);
		return "player";
	}
	
	private boolean isPasswordValid(String password) {
		return true;
	}

	public Player getPlayer() {
		return player;
	}

	public void setPlayer(Player player) {
		this.player = player;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public List<Player> getAllPlayers(){
		return userService.getAllPlayers();
	}
}
